package com.mo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mo.common.Result;
import com.mo.entity.UserRole;
import com.mo.entity.params.UserRoleParam;
import com.mo.service.UserRoleService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
public class UserRoleController {
    @Resource
    private UserRoleService userRoleService;

    @PostMapping("user-role")
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("hasAuthority('sys:system:user:update')")
    public Result addUserRole(@RequestBody UserRoleParam userRoleParam) {
        if (userRoleParam.getRoleIdList().isEmpty()) {
            return Result.error();
        }

        // 先删除
        LambdaQueryWrapper<UserRole> wrapper = Wrappers.<UserRole>lambdaQuery()
                .eq(UserRole::getUserId, userRoleParam.getUserId());
        userRoleService.remove(wrapper);

        // 后添加
        ArrayList<UserRole> userRoles = new ArrayList<>();
        for (Integer ru : userRoleParam.getRoleIdList()) {
            UserRole userRole = new UserRole(null, ru, userRoleParam.getUserId());
            userRoles.add(userRole);
        }
        boolean res = userRoleService.saveBatch(userRoles);
        if (res) {
            return Result.success();
        }
        return Result.error();
    }

    @GetMapping("user-role")
    public Result getUserRole(@RequestParam Integer userId) {
        LambdaQueryWrapper<UserRole> wrapper = Wrappers.<UserRole>lambdaQuery()
                .eq(UserRole::getUserId, userId);
        List<Integer> collect = Optional.ofNullable(userRoleService.list(wrapper))
                .orElse(new ArrayList<>())
                .stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());
        return Result.success(collect);
    }
}
